use std::time::{SystemTime, UNIX_EPOCH};

#[derive(Debug)]
pub struct Todo {
    pub id: i32,
    pub text: String,
    pub completed: bool,
}
impl Todo {
    pub fn edit(&mut self, text: String, completed: bool) {
        self.text = text;
        self.completed = completed
    }
}
#[derive(Debug)]
pub struct TaskList {
    pub tasks: Vec<Box<Todo>>,
}

impl TaskList {
    pub fn new() -> TaskList {
        TaskList { tasks: vec![] }
    }

    pub fn add(&mut self, text: String) {
        self.tasks.push(Box::new(Todo {
            id: rand_task_id(),
            text,
            completed: false,
        }))
    }

    pub fn remove(&mut self, id: i32) {
        let mut itr = self.tasks.iter();
        if let Some(index) = itr.position(|todo| todo.id == id) {
            self.tasks.remove(index);
        }
    }

    pub fn complete(&mut self, id: i32) {
        let mut itr = self.tasks.iter();
        if let Some(index) = itr.position(|todo| todo.id == id) {
            self.tasks[index].completed = true;
        }
    }

    pub fn incomplete(&mut self, id: i32) {
        let mut itr = self.tasks.iter();
        if let Some(index) = itr.position(|todo| todo.id == id) {
            self.tasks[index].completed = false;
        }
    }
    pub fn edit(&mut self, todo: Todo) {
        if let Some(index) = self.tasks.iter().position(|t| t.id == todo.id) {
            self.tasks[index].edit(todo.text, todo.completed);
        }
    }
}

fn rand_task_id() -> i32 {
    // 根据当前时间戳生成todo的id
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("Failed to get timestamp")
        .as_secs() as i32
}
#[cfg(test)]
mod tests {
    use crate::{TaskList, Todo};

    #[test]
    fn test() {
        let mut list = TaskList::new();

        list.add("aaa".to_string());
        println!("{:?}", list);
        let id = list.tasks.first().unwrap().id;
        list.complete(id);
        println!("{:?}", list);
        list.incomplete(id);
        println!("{:?}", list);
        list.edit(Todo {
            id,
            text: "ccc".to_string(),
            completed: true,
        });
        println!("{:?}", list);
        list.remove(id);
        println!("{:?}", list);
    }
}
